import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect:'/welcome',
    children:[
      { path: '/welcome',
      name: 'Welcome',
      component: Welcome,},
      { path: '/users',
      name: 'Users',
      component: Users,}
    ]
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 挂载路由导航守卫
router.beforeEach((to,from,next)=>{
// to酱油访问的路径
// from来自那个路径
// next是一个函数 表示允许放行
// next()放行 next('/login')强制跳转
// 如果跳转到login那么允许
if(to.path==='/login') return next()
// 获取token
const tokenStr=window.sessionStorage.getItem('token');
// 如果获得的token是空 那么去登录
  if(!tokenStr) return next('/login')
  // 否则获取的token不是空 那么随便访问 放行
  next()
})
export default router
